var json2 = {};
$(function() {
	var service = new EbeimService();
	var json = {};
	json.nativeSel = 0;
	json.onlineSel = 0;
	json.useSel = 0;
	var jdataSource = $("#j-dataSource");
	
	var tpl = (function(){
	    var tpl = {};
	    $("script[type='text/ysmart']").each(function(){
	        var t = $(this);
	        tpl[t.attr("data-name")] = t.html();
	    });
	    return tpl;
	})();
	var user = plugin.cookieToJson(document.cookie);
    var jusername = $("#j-username"),
    	jrole = $("#j-role");
    
    jusername.html(user.username);
    if(user.role == "SYSADMIN"){
    	jrole.html("系统管理员");
    }else if(user.role == "ADMIN"){
    	jrole.html("管理员");
    }else{
    	jrole.html("普通用户");
    }
	service.getMonitorPlan(json, callback);
	jdataSource.delegate(".green","click",function(){
		json2.dsName=$(this).attr('ds-name');
		json2.runtime=$(this).attr('ds-time');
		json2.backupCircle=$(this).attr('ds-circle');
		json2.period=$(this).attr('ds-period');
		json2.pageCount=10;
		json2.currentPage=1;
		service.getMonitorDetailPlan(json2, detailForm);
	})
	//数据源详情弹窗
	function detailForm(json){
	    var popform = new plugin.popform({
	        title:"任务执行计划",
	        className:"ui-dialog-sourceDetail",
	        content:plugin.ysmart(tpl.list,json.plan.list || {}),
	        width:860,
	        destroy:true,
	        onHide: function () {
	            // 隐藏弹窗时要执行的回调函数
	        },
	        onShow:function(){
	            // 显示弹窗时要执行的回调函数
	        	$(".ui-dialog-content").css("padding","0");
	        	//分页参数，有些参数是可选的，比如lang，若不传有默认值
	            var pageData = {
	                pno : 1,
	                //总页码
	                total : json.plan.totalPageNum,
	                //总数据条数
	                totalRecords : json.plan.allCount,
	                isShowTotalRecords : false,
	                isShowFirstPageBtn : false,
	                isShowLastPageBtn : false,
	                isShowTotalRecords : false,
	                isShowPrePageBtn : false,
	                isShowNextPageBtn :false,
	                /*isGoPage : false,*/
	                mode : 'click',//默认值是link，可选link或者click
	                click : function(n){
	                	if(!n){
	        	    		n = 1;
	        	    	}
	                    pageData.pno = n;
	                    kkpager.init(pageData);
	                    kkpager.generPageHtml(pageData);
	                    json2.currentPage=n;
	                    service.getMonitorDetailPlan(json2, function(json){
	                    	$("#j-list").html(plugin.ysmart(tpl.listItem,json.plan.list || {}));
	                    });
	                    return false;
	                }
	                }
	            //初始化分页
	            kkpager.init(pageData);
	            //生成分页
	            //有些参数是可选的，比如lang，若不传有默认值
	            kkpager.generPageHtml(pageData);
	        }
	    }).show();
	}
})

timetask();// 启动定时任务
function timetask() {
	onSelect();
	window.setTimeout("timetask()", 180000);
}
function onSelect() {
	var json = {};
	var service = new EbeimService();
	var nativeSel = document.getElementById('nativeSel');// 显示本机
	var useSel = document.getElementById('useSel');// 只显示启用状态
	var onlineSel = document.getElementById('onlineSel');// 只显示在线状态
	if (nativeSel.checked) {
		json.nativeSel = 1;
	} else {
		json.nativeSel = 0;
	}
	if (useSel.checked) {
		json.useSel = 1;
	} else {
		json.useSel = 0;
	}
	if (onlineSel.checked) {
		json.onlineSel = 1;
	} else {
		json.onlineSel = 0;
	}
	service.getMonitorPlan(json, callback);
}
function detailPlanCall(data)
{
	var test=1;
}

function callback(data){
	var native = '';
	var otherPc = '';
	var otherInfo = data.other;
	for ( var o in data) {
		if (o == otherInfo.mac) {
			native = getNativeStr(data[o]);
		} else if (o != 'other') {
			otherPc += getOtherStr(data[o]);
		}
	}
	if (native.length == 0) {
		native = '<h1>本机（我的生活PC）（0个数据源，0个处于启用状态）</h1>';
	}
	otherPc = '<h1>其它设备（' + otherInfo.otherCount + '个数据源，'
			+ otherInfo.activeCount + '个处于启用状态）</h1>' + otherPc;
	$("div.data-source").html(native + otherPc);
}
//设置本机数据源
function getNativeStr(o) {
	var native = "";
	var obj = JSON.parse(o.info);
	native += ' <h1>本机（' + obj.deviceName + '）（' + obj.dsSum + '个数据源，'
			+ obj.dsOnSum + '个处于启用状态）</h1>';
	native += ' <div class="data-group clearfix">';
	native += getOnline(o.list);
	native += '  </div>';
	return native;
}
//设置其他机子数据源
function getOtherStr(o) {
	if (o.list.length != 0) {
		var obj = JSON.parse(o.info);
		var str = '<div class="data-group clearfix">';
		str += ' <label>' + obj.deviceName + '（' + obj.dsSum + '个数据源，'
				+ obj.dsOnSum + '个处于启用状态）</label>';
		str += ' <ul>';
		var obj = JSON.parse(o.info);
		if (obj.status == 0) {
			str += ' <ul>';
			for (i = 0; i < o.list.length; i++) {
				var obj=o.list[i];
				var dsName=obj.name;
				if(dsName.length>14)
				{
					dsName=dsName.substr(0 , 14)+"...";
				}	
				var param='ds-name="'+obj.name+'"  ds-time="'+obj.next_run+'"  ds-circle="'+obj.backup_cycle+'"  ds-period="'+obj.backup_period+'"';
				str += ' <li class="grey j-item" '+param+'>';
				str += ' <a href="javascript:;" title="'+obj.name+'">';
				str += ' <h2>' + dsName+ '</h2>';
				str += ' <p>下次执行时间：未知</p>';
				str += getOffOnlineStatus(obj.ds_status);
				str += '  </a>';
				str += ' </li>';
			}
			str += ' </ul>';
		} else {
			str += getOnline(o.list);
		}
		str += '</div>';
		return str;
	} else {
		return '';
	}
}
//设置在线数据源信息
function getOnline(obj) {
	var str = '<ul>';
	for (i = 0; i < obj.length; i++) {
	var param='ds-name="'+obj[i].name+'"  ds-time="'+obj[i].next_run+'"  ds-circle="'+obj[i].backup_cycle+'"  ds-period="'+obj[i].backup_period+'"';
	var daName=obj[i].name;
	if(daName.length>14)
	{
		daName=daName.substr(0 , 14)+"...";
	}	
	if (obj[i].ds_status == 1) {
			str += '<li class="golden j-item" '+param+' >';
		} else {
			str += '<li class="green j-item" '+param+'>';
		}
		str += ' <a href="javascript:;" title="'+obj[i].name+'">';
		str += ' <h2>' + daName + '</h2>';
		if(obj[i].ds_status == 1){
			str += ' <p>下次执行时间：——</p>';
		}else{
			str += ' <p>下次执行时间：' + getTime(obj[i].next_run) + '</p>';
		}
		str += getStatus(obj[i].ds_status);
		str += '  </a>';
		str += ' </li>';
	}
	str += ' </ul>';
	return str;
}
function getOffOnlineStatus(status) {
	//数据源状态(0启用，1停用)
	var str = '';
	if (status == 0) {
		str = '<p>当前状态：启用  —— 终端不在线</p>'
	}
	if (status == 1) {
		str = '<p>当前状态：停用  —— 终端不在线</p>'
	}
	return str;
}
function getStatus(status) {
	//数据源状态(0启用，1停用)
	var str = '';
	if (status == 0) {
		str = '<p>当前状态：启用</p>'
	}
	if (status == 1) {
		str = '<p>当前状态：停用</p>'
	}
	return str;
}

function getTime(time){
	var date = new Date(time);
	var year=date.getFullYear();
    var month=date.getMonth()+1;
    var day=date.getDate();
    var hour=date.getHours();
    var minute=date.getMinutes();
    var second=date.getSeconds();
    
    return year+"-"+checkTime(month)+"-"+checkTime(day)+" "
    +checkTime(hour)+":"+checkTime(minute)+":"+checkTime(second);     
}
function checkTime(time){
	if(time<10){
		time = "0"+time;
	}
	return time;
}
